package com.huishu.commons.utlis;

import cn.hutool.core.bean.BeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 实体类型转换工具类
 *
 * @author Tuo
 * @Date 2021/7/13 0013
 */
@SuppressWarnings("all")
public class BeanUtils {

    /**
     * 类型转换方法
     *
     * @param source
     *            原类
     * @param clazz
     *            要生成的类型
     * @param <T>
     *            泛型
     * @return
     */
    public static <T> T copyProperties(Object source, Class<T> clazz) {
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(clazz, "Class must not be null");
        T target = null;
        try {
            target = clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        BeanUtil.copyProperties(source, target);
        return target;
    }

    /**
     * Object 对象转 List
     *
     * @param obj
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> castList(Object obj, Class<T> clazz) {
        List<T> result = new ArrayList<T>();
        if (obj instanceof List<?>) {
            for (Object o : (List<?>)obj) {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }

    /**
     * 判断对象中属性值是否全为空
     *
     * @param object
     * @return
     */
    public static boolean checkObjAllFieldsIsNotNull(Object object) {
        if (null == object) {
            return false;
        }
        try {
            for (Field f : object.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                if (StringUtils.isBlank(f.get(object).toString())) {
                    return false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 判断对象中属性值是否全不为空
     *
     * @param object
     * @param name
     *            排除哪个字段
     * @return
     */
    public static boolean checkObjAllFieldsIsNotNull(Object object, String name) {
        if (null == object) {
            return false;
        }
        try {
            for (Field f : object.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                if (f.getName().equals(name)) {
                    continue;
                }
                if (StringUtils.isBlank(f.get(object).toString())) {
                    return false;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}
